package com.xr.generator.controller;

import com.xr.generator.entity.TableNameDto;
import com.xr.generator.service.SysGeneratorService;
import com.xr.generator.utils.PageUtil;
import com.xr.generator.utils.Query;
import com.xr.common.axios.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 代码生成器控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/generator")
public class SysGeneratorController {

    @Autowired
    private SysGeneratorService sysGeneratorService;

    @Autowired
    private HttpServletResponse response;

    /**
     * 分页查询表信息
     */
    @GetMapping("/selectPage")
    public R list(int current, int size, String tableName) {
        Map<String, Object> map = new HashMap<>();
        map.put("page", current);
        map.put("limit", size);
        map.put("tableName", tableName);
        PageUtil pageUtil = sysGeneratorService.queryList(new Query(map));
        return R.ok(pageUtil);
    }

    /**
     * 根据表名生成代码
     */
    @GetMapping("/generateBatch")
    public void generateBatch(TableNameDto tableNameDto) {
        String[] tableNames = tableNameDto.getTableNameList().toArray(new String[0]);
        try {
            byte[] data = sysGeneratorService.generatorCode(tableNames);
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"generated_code.zip\"");
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");
            IOUtils.write(data, response.getOutputStream());
        } catch (IOException e) {
            log.error("代码生成失败");
            e.printStackTrace();
        }
    }

}
